﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Update
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private const string serviceName = "SFJDService";
        private const string mainExe = "SFJDManagement.exe";
        private const string serviceExe = "SFJDService.exe";
        private const string trayExe = "SFJDTray.exe";
        private string pathProgram;
        private string pathUpdateSource;
        ServiceHelper serviceHelper = new ServiceHelper();

        public MainWindow()
        {
            InitializeComponent();
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            ini();
            this.SetPath();
            this.Uninstall();
            this.Install();
        }

        private void ini()
        {
            this.Title = "司法鉴定管理程序";
            //this.WindowStyle = WindowStyle.None;
            //this.BorderThickness = new Thickness(0, 0, 0, 0);
            //this.AllowsTransparency = true;
            //this.Background = Brushes.Transparent;
            Label label1 = new Label();
            label1.Width = 500;
            label1.HorizontalAlignment = HorizontalAlignment.Center;
            label1.HorizontalContentAlignment = HorizontalAlignment.Center;
            label1.VerticalContentAlignment = VerticalAlignment.Center;
            label1.FontSize = 100;
            label1.Foreground = Brushes.Red;
            label1.Content = "正在升级...\n此处是动画";
            this.gridRoot.Children.Add(label1);
        }

        private void SetPath()
        {
            RegistryHelper registryHelper = new RegistryHelper();
            this.pathProgram = registryHelper.GetRegistryData("RootPath");
            this.pathUpdateSource = "E:\\收到的文件\\UpDate\\";
        }

        private void Uninstall()
        {
            this.KillProcess(mainExe);
            this.KillProcess(serviceExe);
            this.KillProcess(trayExe);
            serviceHelper.StopService(serviceName);
            serviceHelper.UninstallService(serviceName);
            this.DelteFiles(this.pathProgram + "\\");
        }

        private void KillProcess(string processName)
        {
            Process[] Proc = Process.GetProcessesByName(processName);
            DateTime startTime = new DateTime();
            int m, killId = 0;
            for (m = 0; m < Proc.Length; m++)
            {
                if (startTime < Proc[m].StartTime)
                {
                    startTime = Proc[m].StartTime;
                    killId = m;
                }
            }
            if (Proc[killId].HasExited == false)
            {
                Proc[killId].Kill();
            }
        }

        private void Install()
        {
            this.CopyDirectory(this.pathUpdateSource, this.pathProgram);
            Process p = new Process();
            p.StartInfo.FileName = pathProgram + "\\SFJDTray.exe";
            p.Start();
            //serviceHelper.InstallmyService(null, this.pathProgram + "\\" + serviceName);
            //serviceHelper.ChangeServiceStartType(2, serviceName);
            //serviceHelper.StartService(serviceName);
        }

        private void DelteFiles(string folder)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(folder);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        //subdir.Delete(true);          //删除子目录和文件
                        DelteFiles(i.FullName);
                        subdir.Delete();
                    }
                    else
                    {
                        if(i.FullName.Substring(i.FullName.Length - 4, 4) != ".xml")
                        {
                            File.Delete(i.FullName);      //删除指定文件
                        }
                    }
                }
            }
            catch 
            {
                throw;
            }
        }

        private void CopyDirectory(string srcPath, string destPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //获取目录下（不包含子目录）的文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)     //判断是否文件夹
                    {
                        if (!Directory.Exists(destPath + "\\" + i.Name))
                        {
                            Directory.CreateDirectory(destPath + "\\" + i.Name);   //目标目录下不存在此文件夹即创建子文件夹
                        }
                        CopyDirectory(i.FullName, destPath + "\\" + i.Name);    //递归调用复制子文件夹
                    }
                    else
                    {
                        File.Copy(i.FullName, destPath + "\\" + i.Name, true);      //不是文件夹即复制文件，true表示可以覆盖同名文件
                    }
                }
            }
            catch 
            {
                throw;
            }
        }
    }
}
